import { FastifyPluginAsync } from 'fastify'

const example: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
  fastify.get('/', async function (request, reply) {
    return 'this is an example'
  });
  fastify.get('/test', async function (request, reply) {

    const db = fastify.mongo.db;
    if(!db)return {};
    const result = await db.collection('test').find({}).toArray()
    return result
  })
  fastify.get('/flat', async function (request, reply) {

    const db = fastify.mongo.db;
    if(!db)return {};
    const result = await db.collection('test').aggregate([
      // { $match: { } },
      {
        $project: {
          _id: 1,
          name: 1,
          allMessages: {
            $concatArrays: [
              // 将父级 message 包装成与 comments 相同结构的数组
              [{
                message: "$message",
                type: "parent",
                status: "$status" // 可以自定义父级的status
              }],
              // 保留原有的 comments 数组
              "$comments"
            ]
          }
        }
      },
      { $unwind: "$allMessages" },
      {
        $project: {
          postId: "$_id",
          postName: "$name",
          message: "$allMessages.message",
          type: "$allMessages.type",
          status: "$allMessages.status"
        }
      }
    ]).toArray();

    return result
  })
  fastify.post('/create', async function (request, reply) {
    const db = fastify.mongo.db;
    if(!db)return {};
    const { name, message, comments, status } = request.body;
    const result = await db.collection('test').insertOne({ name,message, comments, status });
    return result
  })
}

export default example
